<?php

namespace App\Library;

use OSS\Core\OssException;
use OSS\Http\RequestCore_Exception;
use OSS\OssClient;

class OssLib
{
    private static array $oss;
    private static OssClient $client;

    /**
     * client
     * @return OssClient
     */
    public static function client(): OssClient
    {
        if (!empty(self::$oss)) return self::$client;
        self::$oss = config('oss');
        self::$client = new OssClient(self::$oss['key'], self::$oss['secret'], self::$oss['endpoint']);
        return self::$client;
    }

    /**
     * 上传文件
     * @param string $url
     * @param string $path
     * @param string $mimeType
     * @return ?array
     * @throws OssException
     * @throws RequestCore_Exception
     */
    public static function put(string $url, string $path, string $mimeType): ?array
    {
        return self::$client->putObject(self::$oss['bucket'], substr(str_replace(self::$oss['url'], '/', $url), 1),
            file_get_contents($path), ['Content-Type' => $mimeType]);
    }

    /**
     * 上传文件
     * @param string $fileId
     * @return ?array
     * @throws OssException
     * @throws RequestCore_Exception
     */
    public static function get(string $fileId): ?array
    {
        return self::client()->getObjectMeta(self::$oss['bucket'], fileIdToDir($fileId));
    }
}
